package com.yk.silence.rxmvp.base;

import com.google.gson.JsonParseException;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.text.ParseException;

import io.reactivex.observers.DisposableObserver;
import retrofit2.HttpException;

public abstract class BaseObserver<T> extends DisposableObserver<T> {
    protected BaseView mView;
    /**
     * 解析数据失败
     */
    public static final int PARSE_ERROR = 1001;
    /**
     * 网络问题
     */
    public static final int BAD_NETWORK = 1002;
    /**
     * 连接错误
     */
    public static final int CONNECT_ERROR = 1003;
    /**
     * 连接超时
     */
    public static final int CONNECT_TIMEOUT = 1004;

    public BaseObserver(BaseView mView) {
        this.mView = mView;
    }

    @Override
    protected void onStart() {
        if (mView != null) {
            mView.showLoading();
        }
    }

    @Override
    public void onNext(T t) {
        try {
            BaseModel model = (BaseModel) t;
            if (model.getCode() == 0) {
                onSuccess(t);
            } else {
                if (mView != null) {
                    mView.onErrorCode(model);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            onError(ex.toString());
        }

    }

    @Override
    public void onError(Throwable e) {
        if (mView != null) {
            mView.hideLoading();
        }
        if (e instanceof HttpException) {//HTTP错误
            onException(BAD_NETWORK);
        } else if (e instanceof ConnectException ||
                e instanceof UnknownHostException) {//连接错误
            onException(CONNECT_ERROR);
        } else if (e instanceof InterruptedException) {//网络超时
            onException(CONNECT_TIMEOUT);
        } else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {//解析失败
            onException(PARSE_ERROR);
        } else {
            if (e != null) {
                onError(e.toString());
            } else {
                onError("未知错误");
            }
        }
    }

    @Override
    public void onComplete() {
        if (mView != null) {
            mView.hideLoading();
        }

    }

    /**
     * 异常
     *
     * @param unKnowError
     */
    private void onException(int unKnowError) {
        switch (unKnowError) {
            case CONNECT_ERROR:
                onError("连接错误");
                break;
            case CONNECT_TIMEOUT:
                onError("连接超时");
                break;
            case PARSE_ERROR:
                onError("数据解析失败");
                break;
            case BAD_NETWORK:
                onError("网络错误");
                break;
        }
    }

    /**
     * 成功
     *
     * @param t
     */
    public abstract void onSuccess(T t);

    /**
     * 失败
     *
     * @param msg
     */
    public abstract void onError(String msg);
}
